package cn.actoncode.boot.framework.common.http.okhttp;

import cn.actoncode.boot.framework.common.exception.ServiceErrorException;
import cn.actoncode.boot.framework.common.http.RequestHttp;
import cn.actoncode.boot.framework.common.http.RoutinePostRequestExecutor;
import cn.actoncode.boot.framework.common.http.enums.PlatformType;
import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * .
 *
 * @author bin
 */
@Slf4j
public class OkHttpRoutinePostRequestExecutor extends RoutinePostRequestExecutor<OkHttpClient, OkHttpProxyInfo> {
    public OkHttpRoutinePostRequestExecutor(RequestHttp requestHttp) {
        super(requestHttp);
    }

    @Override
    public ObjectNode execute(String uri, Map<String, String> headers, String postEntity, PlatformType platformType) throws ServiceErrorException, IOException {
        Headers.Builder hb = new Headers.Builder();
        if (CollUtil.isNotEmpty(headers)) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                hb.add(entry.getKey(), entry.getValue());
            }
        }
        RequestBody body = RequestBody.Companion.create(postEntity, MediaType.parse("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(uri).headers(hb.build()).post(body).build();
        Response response = requestHttp.getRequestHttpClient().newCall(request).execute();
        return this.handleResponse(platformType, Objects.requireNonNull(response.body()).string());
    }

}
